#include "ZipValidator.h"
#include <vector>
#include <algorithm>
using namespace std;

const string ZIP_FILE_EXTENSION = "zip";
const string ZIP_NEWER_FILE_EXTENSION = "zipx";

ZipValidator::ZipValidator()
{

}

bool ZipValidator::validateZipPath(const char* path)
{
    string zipPath(path);
    vector<string> extensions;
    extensions.push_back(ZIP_FILE_EXTENSION);
    extensions.push_back(ZIP_NEWER_FILE_EXTENSION);

    int index = zipPath.find_last_of(".");

    //check file extension separator exists
    if (index == string::npos)
        return false;

    string expectedExtension = zipPath.substr(index + 1);

    vector<string>::iterator found = std::find(extensions.begin(), extensions.end(), expectedExtension);

    return found != extensions.end();
}

bool ZipValidator::validateZipFileSignature(const char* path)
{
    bool res = false;
    FILE* file = fopen(path, "rb");
    unsigned int signatureReaded = 0;
    if (file)
    {
        int readBytes = fread(&signatureReaded, sizeof (char), sizeof (FILE_HEADER_SIGNATURE), file);
        res = (readBytes == sizeof (FILE_HEADER_SIGNATURE)) &&
                (signatureReaded == FILE_HEADER_SIGNATURE);
        fclose(file);
    }
    return res;
}

ErrorCode ZipValidator::validateZip(const char* path)
{
    if (validateZipPath(path) == 0)
        return INVALID_EXTENSION;
    if (validateZipFileSignature(path) == 0)
        return NOT_A_ZIP_FILE;

    return VALID_ZIP_FILE;
}